﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LaoLuo
{
    public class DateTimeFormatter
    {
        private static ConcurrentDictionary<string, DateTimeFormatter> _cache = new ConcurrentDictionary<string, DateTimeFormatter>();
        private static readonly string spliter = "~";

        private DateTimeFormatter(string format, string defaultString)
        {
            this.FormatString = format;
            this.DefaultString = defaultString;
        }

        public string FormatString { get; protected set; }

        public string DefaultString { get; protected set; }

        public string Format(params DateTime?[] items)
        {
            foreach (var value in items)
            {
                if (value.HasValue)
                {
                    return value.Value.ToString(FormatString);
                }
            }

            return DefaultString;
        }

        public static DateTimeFormatter GetDateTimeFormatter(string format, string defaultString = "")
        {
            return _cache.GetOrAdd(GetKey(format, defaultString), s => new DateTimeFormatter(format,
                                                                                             defaultString));
        }

        private static string GetKey(string format, string defaultString)
        {
            return format + spliter + defaultString;
        }
    }
}
